/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * WynikWyszukiwania.java
 *
 * Created on 2011-05-06, 15:48:38
 */
package Interface;

import org.db2.project.airline.dao.DAOException;
import org.db2.project.airline.dto.FlightPlanQueryCriteria;
import org.db2.project.airline.model.FlightClassType;
import org.db2.project.airline.model.FlightPlan;
import org.db2.project.airline.service.FlightClassPriceService;
import org.db2.project.airline.service.FlightPlanService;
import org.db2.project.airline.utils.Utils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author Martyna
 */
public class WynikWyszukiwania extends javax.swing.JFrame {

    private final String[] columnNames = new String[]{"Wylot", "Przylot", "Kod lotu",
            "Klasa", "Cena", "Data Wylotu", "Godzina wylotu"};

    private final FlightPlanService flightPlanService = new FlightPlanService();

    private final FlightClassPriceService flightClassPriceService = new FlightClassPriceService();

    private FlightPlanQueryCriteria flightPlanQueryCriteria;

    private List<FlightPlan> departureFlightPlans;

    private List<FlightPlan> arrivalFlightPlans;
    private wyszukaniePolaczenia WyszukaniePolaczenia;

    /**
     * Creates new form WynikWyszukiwania
     */
    public WynikWyszukiwania(FlightPlanQueryCriteria flightPlanQueryCriteria, wyszukaniePolaczenia WyszukaniePolaczenia) {

        // assings the namesake variable
        this.flightPlanQueryCriteria = flightPlanQueryCriteria;
        this.WyszukaniePolaczenia = WyszukaniePolaczenia;

        initComponents();

        fillComponentsData();
    }

    private void fillComponentsData() {
        try {
            departureFlightPlans = flightPlanService.findPlan(flightPlanQueryCriteria.getDeparture(),
                    flightPlanQueryCriteria.getArrival(), flightPlanQueryCriteria.getFlightClassType(),
                    flightPlanQueryCriteria.getDepartureDate(), flightPlanQueryCriteria.getArrivalDate(),
                    flightPlanQueryCriteria.isTwoDaysSpan());

            jTable1.setModel(createTableModel(departureFlightPlans, flightPlanQueryCriteria.getFlightClassType()));

            jTable2.setVisible(!flightPlanQueryCriteria.isOneWay());

            if (!flightPlanQueryCriteria.isOneWay()) {

                arrivalFlightPlans = flightPlanService.findPlan(flightPlanQueryCriteria.getArrival(),
                        flightPlanQueryCriteria.getDeparture(), flightPlanQueryCriteria.getFlightClassType(),
                        flightPlanQueryCriteria.getDepartureDate(), flightPlanQueryCriteria.getArrivalDate(),
                        flightPlanQueryCriteria.isTwoDaysSpan());

                jTable2.setModel(createTableModel(arrivalFlightPlans, flightPlanQueryCriteria.getFlightClassType()));
            }
        } catch (DAOException e) {
            // TODO handle the exception
            throw new RuntimeException(e);
        }
    }

    private TableModel createTableModel(List<FlightPlan> flightPlans, FlightClassType flightClassType) throws DAOException {

        Object[][] data = new Object[flightPlans.size()][7];
        BigDecimal flightClassPrice;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");

        int index = 0;
        for (FlightPlan flightPlan : flightPlans) {
            flightClassPrice = flightClassPriceService.getFlightPrice(flightPlan, flightClassType);

            data[index][0] = flightPlan.getFlightRoute().getDepartureAirport().getName();
            data[index][1] = flightPlan.getFlightRoute().getDestinationAirport().getName();
            data[index][2] = flightPlan.getCode();
            data[index][3] = Utils.capitalize(flightPlanQueryCriteria.getFlightClassType().toString());
            data[index][4] = flightClassPrice != null ? flightClassPrice.toString() : null;

            data[index][5] = dateFormat.format(flightPlan.getDepartureTime());
            data[index][6] = dateFormat.format(flightPlan.getArrivalTime());

            index++;
        }

        return new DefaultTableModel(data, columnNames);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Rezerwuj");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        jButton2.setText("Wstecz");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 215, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addGap(50, 50, 50))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(47, 47, 47))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:

        // TODO make sure if both departure and arrival airports has been selected
        if (jTable1.getSelectedRow() == -1
                || (!flightPlanQueryCriteria.isOneWay() && jTable2.getSelectedRow() == -1)) {

            String msg = "Prosze wybrać lot docelowy i powrotny";
            if (flightPlanQueryCriteria.isOneWay()) {
                msg = "Prosze wybrać lot docelowy";
            }

            JOptionPane.showMessageDialog(this, msg, "Proszę wybrać lot.", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        FlightPlan departureFligthPlan = null;
        FlightPlan arrivalFlightPlan = null;

        departureFligthPlan = departureFlightPlans.get(jTable1.getSelectedRow());

        if (!flightPlanQueryCriteria.isOneWay()) {

            arrivalFlightPlan = arrivalFlightPlans.get(jTable2.getSelectedRow());
        }

        new ZarezerwujBilet(departureFligthPlan, arrivalFlightPlan,
                flightPlanQueryCriteria.getFlightClassType(), flightPlanQueryCriteria.isOneWay(), this)
                .setVisible(true);

        setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
WyszukaniePolaczenia.setVisible(true);
this.setVisible(false);// TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                // new WynikWyszukiwania().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables
}
